import config from './config'

class Http {
  request(method, api, data, loading = false, toast = true) {
    
    let info = {
      url: config.domain + '/api/service/' + api,
      data,
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token') || ''
      },
      method: method,
      timeout: 0
    }

    return new Promise((resolve, reject) => {
      if (loading) {
        wx.showLoading({
          title: '加载中',
          mask: true,
        })
      }
      wx.request({
        ...info,
        success: (result) => {
          
          if (result.statusCode === 401) {
            wx.navigateTo({
              url: '/service/login/login',
            })
            reject(result)
          }

          if (result.data.code !== 1) {
            if (toast) {
              wx.showToast({
                title: (result && result.data && result.data.msg) ? result.data.msg : '请稍后重试',
                icon: 'none',
                duration: 2000
              })
            }else{
              reject(result)
            }
            
          }else{
            resolve(result.data)
          }
          
        },
        fail: (res) => {
          reject(res)
        },
        complete: (res) => {
          wx.hideLoading({
            noConflict: true
          })
        },
      })
    })
  }

  post(url, data, loading, toast) {
    
    return this.request('POST', url, data, loading, toast)
  }

  get(url, data, loading, toast) {
    return this.request('GET', url, data, loading, toast)
  }

  upload(file, data, loading = false, toast = true){

    return new Promise((resolve, reject) => {
      if (loading) {
        wx.showLoading({
          title: '加载中',
          mask: true,
        })
      }
      wx.uploadFile({
        url: config.domain  +'/api/common/upload', //仅为示例，非真实的接口地址
        filePath: file,
        name: 'file',
        formData: {
          token: wx.getStorageSync('token'),
          ...data
        },
        success: (result) => {
          result.data = JSON.parse(result.data)
          if (result.statusCode === 401) {
            wx.navigateTo({
              url: '/service/login/login',
            })
            reject(result)
          }

          if (result.data.code !== 1) {
            if (toast) {
              wx.showToast({
                title: (result && result.data && result.data.msg) ? result.data.msg : '请稍后重试',
                icon: 'none',
                duration: 2000
              })
            }
            reject(result)
          }
          resolve(result.data)
        },
        fail: (res) => {
          
          reject(res)
        },
        complete: (res) => {
         
          wx.hideLoading({
            noConflict: true
          })
        },
      })
      
    })
    
  }

  chooseImg(source,loading,toast,sizeType){
    return new Promise((resolve, reject)=>{
      wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: source,
        sizeType: sizeType ? sizeType : ['compressed'],
        camera: 'back',
        success: (res)=> {
          this.upload(res.tempFiles[0].tempFilePath,{
            type: 'image'
          },loading,toast).then(res=>{
            resolve(res)
          }).catch(err => {
            reject(err)
          })
        },
        fail: (err)=>{
          reject(err)
        }
      })
    })
    
  }

  chooseLocation(lat = '',lng = ''){
    return new Promise((resolve, reject)=>{
      let params = {}
      if(lat){
        params = {
          latitude: lat,
          longitude: lng,
        }
      }
      wx.chooseLocation({
        ...params,
        success:(res)=>{
          let lat = res.latitude
          let lng = res.longitude
          let name = res.name
          this.post('user/getlocation', {
            lat: res.latitude,
            lng: res.longitude
          }).then(res => {
            let city = ''
            let province = res.data.regeocode.addressComponent.province
            if (res.data.regeocode.addressComponent.city === '[]' || res.data.regeocode.addressComponent.city.length === 0) {
              city = province
            } else {
              city = res.data.regeocode.addressComponent.city
            }
            let district = res.data.regeocode.addressComponent.district
            name = name || res.data.regeocode.aois[0].name || res.data.regeocode.formatted_address
            let data = {
              city,
              province,
              district,
              name,
              lat,
              lng
            }
            resolve(data)
          }).catch(err => {
            reject(err)
          })
        },
        fail:(e)=>{
          let data = {
            province: '河南省',
            city: '郑州市',
            district: '中原区',
            name: '郑州市',
            lat: '34.74725',
            lng: '113.62493'
          }
          reject(data)
          // wx.getSetting({
          //   withSubscriptions: true,
          //   success:(res)=>{
          //     console.log(res)
          //     let authSetting = res.authSetting
          //     if(!authSetting['scope.userLocation']){
          //       wx.showModal({
          //         title: '您未开启地理位置授权',
          //         content: '请在设置中打开位置授权，以便我们能够更好的提供服务',
          //         success (res) {
          //           if (res.confirm) {
          //             wx.openSetting()
          //           } else if (res.cancel) {
          //             let data = {
          //               province: '河南省',
          //               city: '郑州市',
          //               district: '中原区',
          //               name: '郑州市',
          //               lat: '34.74725',
          //               lng: '113.62493'
          //             }
          //             reject(data)
          //           }
          //         }
          //       })
          //     }
          //   }
          // })
        }
      })
    })

  }

  getLocation(lat = '',lng = ''){
    return new Promise((resolve, reject)=>{
      wx.getLocation({
        type: 'wgs84',
        success:(res)=>{
          console.log('res1111',res);
          let lat = res.latitude
          let lng = res.longitude
          this.post('user/getlocation', {
            lat: res.latitude,
            lng: res.longitude
          }).then(res => {
            let city = ''
            let province = res.data.regeocode.addressComponent.province
            if (res.data.regeocode.addressComponent.city === '[]' || res.data.regeocode.addressComponent.city.length === 0) {
              city = province
            } else {
              city = res.data.regeocode.addressComponent.city
            }
            let district = res.data.regeocode.addressComponent.district
            let name = res.data.regeocode.aois[0].name || res.data.regeocode.formatted_address
            let data = {
              city,
              province,
              district,
              name,
              lat,
              lng
            }
            resolve(data)
          }).catch(err => {
            reject(err)
          })
        },
        fail:(e)=>{
          wx.getSetting({
            withSubscriptions: true,
            success:(res)=>{
              let authSetting = res.authSetting
              if(!authSetting['scope.userLocation']){
                wx.showModal({
                  title: '您未开启地理位置授权',
                  content: '请在设置中打开位置授权，以便我们能够更好的提供服务',
                  success (res) {
                    if (res.confirm) {
                      wx.openSetting()
                    } else if (res.cancel) {
                      let data = {
                        province: '河南省',
                        city: '郑州市',
                        district: '中原区',
                        name: '郑州市',
                        lat: '34.74725',
                        lng: '113.62493'
                      }
                      reject(data)
                    }
                  }
                })
              }
            }
          })
        }
      })
    })
  }
}

const http = new Http()
export default http